<template>
  <view class="ai-page">
    <!-- 顶部 -->
    <view class="nav">
      <view class="nav-left" @click="goBack">←</view>
      <view class="nav-title">AI 问诊</view>
      <view class="nav-right" @click="resetAll">重置</view>
    </view>

    <!-- 聊天区域（重构） -->
    <view class="chat-container">
      <scroll-view 
        class="chat-messages" 
        scroll-y="true" 
        :scroll-top="scrollTop"
        scroll-with-animation="true"
      >
        <view class="message-list">
          <view v-if="messages.length === 0" class="welcome-message">
            <view class="ai-message">
              <view class="avatar ai-avatar">
                <text class="iconfont icon-robot"></text>
              </view>
              <view class="message-content ai-content">
                <text>您好！我是云诊康医疗助手，有什么健康问题可以咨询我。</text>
              </view>
            </view>
          </view>
          <view v-for="(m, i) in messages" :key="i" class="message-item">
            <view v-if="m.type==='user'" class="user-message">
              <view class="message-content user-content">
                <text>{{ m.content }}</text>
              </view>
              <view class="avatar user-avatar">
                <text class="iconfont icon-user"></text>
              </view>
            </view>
            <view v-else class="ai-message">
              <view class="avatar ai-avatar">
                <text class="iconfont icon-robot"></text>
              </view>
              <view class="message-content ai-content">
                <text>{{ m.content }}</text>
                <view v-if="m.loading" class="typing-indicator">
                  <text class="dot"></text>
                  <text class="dot"></text>
                  <text class="dot"></text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 输入区域 -->
      <view class="chat-input">
        <view class="input-wrapper">
          <input 
            class="message-input"
            v-model="inputMessage"
            placeholder="请输入您的问题..."
            :disabled="isLoading"
            @confirm="sendMessage"
            confirm-type="send"
          />
          <button 
            class="send-btn"
            :class="{ 'disabled': !inputMessage.trim() || isLoading }"
            @click="sendMessage"
            :disabled="!inputMessage.trim() || isLoading"
          >
            <text v-if="!isLoading" class="iconfont icon-send"></text>
            <text v-else class="loading-text">发送中</text>
          </button>
        </view>
      </view>
    </view>

    <view class="safe-bottom"></view>
  </view>
</template>

<script>
import { chatWithAI } from '@/api/ai'
export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      scrollTop: 0
    }
  },
  onLoad(){
    this.initChat()
  },
  methods: {
    initChat(){
      // 欢迎消息
      this.messages = []
      this.messages.push({ type: 'ai', content: '您好！我是云诊康医疗助手，请描述您的症状或问题。' })
      this.scrollToBottom()
    },
    async sendMessage(){
      if (!this.inputMessage.trim() || this.isLoading) return
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      // 用户消息
      this.messages.push({ type: 'user', content: userMessage, timestamp: new Date() })
      // AI 占位
      const aiIndex = this.messages.length
      this.messages.push({ type: 'ai', content: '', loading: true, timestamp: new Date() })
      this.isLoading = true
      this.scrollToBottom()
      try {
        await this.sendChatRequest(userMessage, aiIndex)
      } catch (e) {
        console.error('发送失败', e)
        this.messages[aiIndex] = { type: 'ai', content: '抱歉，服务暂时不可用，请稍后再试。', loading: false, timestamp: new Date() }
      } finally {
        this.isLoading = false
      }
    },
    async sendChatRequest(message, index){
      try{
        const resp = await chatWithAI(message)
        if (resp) {
          if (resp.data) {
            this.handleStreamResponse(resp.data, index)
          } else if (resp.code === 200) {
            this.handleStreamResponse(resp, index)
          } else {
            throw new Error('响应数据为空或格式错误')
          }
        } else {
          throw new Error('响应为空')
        }
      }catch(err){
        console.error('API请求失败', err)
        throw err
      }
    },
    handleStreamResponse(data, index){
      if (typeof data === 'string') {
        this.displayResponse(data, index)
      } else if (data && typeof data === 'object') {
        const text = data.data || data.content || data.message || JSON.stringify(data)
        this.displayResponse(text, index)
      } else {
        this.messages[index] = { type: 'ai', content: '抱歉，响应数据格式异常。', loading: false, timestamp: new Date() }
      }
    },
    displayResponse(full, index){
      if (!full || typeof full !== 'string') {
        this.messages[index] = { type: 'ai', content: '抱歉，响应内容为空。', loading: false, timestamp: new Date() }
        return
      }
      let i = 0
      const typeWriter = () => {
        if (i < full.length) {
          this.messages[index].content = full.substring(0, i + 1)
          i++
          this.scrollToBottom()
          setTimeout(typeWriter, 30)
        } else {
          this.messages[index].loading = false
          this.scrollToBottom()
        }
      }
      this.messages[index].loading = false
      typeWriter()
    },
    scrollToBottom(){
      this.$nextTick(()=>{ this.scrollTop = 99999 })
    },
    resetAll(){
      this.initChat()
    },
    goBack(){
      const pages = getCurrentPages && getCurrentPages()
      if (pages && pages.length > 1) uni.navigateBack({ delta: 1 })
      else (uni.switchTab ? uni.switchTab({ url: '/pages/index' }) : uni.reLaunch({ url: '/pages/index' }))
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-page { background: #f5f5f5; height: 100vh; display:flex; flex-direction: column; }
.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 1100; display:flex; align-items:center; justify-content:space-between; height: calc(var(--status-bar-height) + 88rpx); padding: 0 20rpx; padding-top: var(--status-bar-height); background:#fff; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
  .nav-left, .nav-right { width: 88rpx; color:#333; }
  .nav-right { text-align: right; }
  .nav-title { flex:1; text-align:center; font-weight:600; color:#333; }
}

/* 重构聊天样式 */
.chat-container { 
  /* 使用固定定位明确可视高度，避免在小程序/H5下 scroll-view 因 flex 计算异常而无法滚动 */
  position: fixed; left: 0; right: 0; 
  top: calc(var(--status-bar-height) + 88rpx);
  bottom: calc(120rpx + var(--window-bottom));
  display:flex; flex-direction:column; overflow:hidden;
}
.chat-messages { flex:1; height: 100%; padding: 20rpx; background:#f7f8fa; }
.message-list { padding-bottom: 120rpx; }
.message-item { margin-bottom: 26rpx; }
.user-message, .ai-message { display:flex; align-items:flex-start; gap: 20rpx; }
.user-message { justify-content: flex-end; }
.avatar { width: 64rpx; height: 64rpx; border-radius: 50%; display:flex; align-items:center; justify-content:center; font-size: 28rpx; flex-shrink:0; }
.user-avatar { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:#fff; }
.ai-avatar { background: #f0f0f0; color:#666; border: 2rpx solid #e8e8e8; }
.message-content { max-width: 520rpx; padding: 18rpx 24rpx; border-radius: 18rpx; font-size: 28rpx; line-height: 1.6; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04); }
.user-content { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:#fff; margin-left: 80rpx; }
.ai-content { background:#fff; color:#333; margin-right: 80rpx; border: 2rpx solid #e8e8e8; }
.typing-indicator { display:flex; gap:8rpx; margin-top: 8rpx; }
.typing-indicator .dot { width: 8rpx; height: 8rpx; background:#999; border-radius:50%; animation: typing 1.4s infinite; }
.typing-indicator .dot:nth-child(2){ animation-delay: .2s }
.typing-indicator .dot:nth-child(3){ animation-delay: .4s }
@keyframes typing { 0%,60%,100%{ transform: translateY(0); opacity:.4 } 30%{ transform: translateY(-8rpx); opacity:1 } }

.chat-input { position: fixed; left: 0; right: 0; bottom: var(--window-bottom); background:#fff; padding: 10rpx 14rpx; border-top: 2rpx solid #e8e8e8; box-sizing: border-box; z-index: 1050; }
.input-wrapper { display:flex; align-items:center; gap: 10rpx; background:#f8f8f8; border-radius: 999rpx; padding: 8rpx 14rpx; }
.message-input { flex:1; height: 60rpx; font-size: 28rpx; background:transparent; border:none; outline:none; }
.send-btn { width: 64rpx; height: 64rpx; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:#fff; border:none; display:flex; align-items:center; justify-content:center; font-size: 22rpx; }
.send-btn.disabled { background:#ccc; color:#999; }
.iconfont { font-family: "iconfont" }
.safe-bottom { height: 0; }
</style>
